package gapidt.plugin.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import gapidt.plugin.wizards.WsdlGeneratorWizard;

import org.apache.log4j.Logger;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;


public class GenerateWsdlFromMenu implements IObjectActionDelegate {
	
	static Logger logger = Logger.getLogger(GenerateWsdlFromMenu.class);
	
	public static final String ID = GenerateWsdlFromMenu.class.getCanonicalName(); 

	List<IType> selectedTypes = new ArrayList<IType>();

	@Override
	@SuppressWarnings("unchecked")
	public void selectionChanged(IAction action, ISelection selection) {
		selectedTypes.clear();
		if(selection != null){
			Iterator<Object> it = (Iterator<Object>) ((IStructuredSelection)selection).iterator();
			while(it.hasNext()){
				Object next = it.next();
				if(next instanceof IJavaElement)
					addTypes((IJavaElement) next);
			}
		}
	}
	
	private void addTypes(IJavaElement javaElement){
		if(javaElement instanceof IType)
			selectedTypes.add((IType) javaElement);
		else if(javaElement instanceof ICompilationUnit){
			try {
				for(IType type : ((ICompilationUnit) javaElement).getAllTypes())
					selectedTypes.add(type);
			} catch (JavaModelException e) {
				e.printStackTrace();
			}
		}else if(javaElement instanceof IParent){
			try {
				for(IJavaElement c : ((IParent) javaElement).getChildren())
					addTypes(c);
			} catch (JavaModelException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run(IAction action) {
		if(selectedTypes.size() > 0){
			IJavaProject javaProject = JavaCore.create(selectedTypes.get(0).getResource().getProject());
			WsdlGeneratorWizard wizard = new WsdlGeneratorWizard(selectedTypes.toArray(new IType[]{}), javaProject);
			WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().getSite().getShell(), wizard);
			dialog.create();
			dialog.open();
		}else
			logger.debug("Can not generate wsdl, no types selected");
	}

	@Override
	public void setActivePart(IAction arg0, IWorkbenchPart part) {
		
	}
}
